package com.cmcc.groupcontacts.firewall.adapter;

import java.util.ArrayList;

import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.cmcc.groupcontacts.firewall.activity.FirewallConfigKeywordsActivity;
import com.cmcc.groupcontacts.firewall.business.FirewallConfigBusiness;
import com.cmcc.groupcontacts.firewall.dao.model.KeywordsVO;
import com.cmcc.groupcontacts.util.ExceptionHandler;
import com.cmcc.groupcontacts.util.StringUtil;
import com.yinhai.activity.R;

/**
 * 
 * 信息拦截关键字Adapter
 * 
 * @author 
 * 
 */
public class FirewallConfigKeywordsAdapter extends BaseAdapter<KeywordsVO> {
	/**
	 * 视图缓存
	 */
	public final class ViewCache {
		public TextView txtKeywords;
		public ImageButton btnDelete;
	}

	private ViewCache viewCache = null;

	public FirewallConfigKeywordsAdapter(Context context, ArrayList<KeywordsVO> keywordsList) {
		super(R.layout.firewall_config_keywords_item, context, keywordsList);
	}

	@Override
	protected void setViewCache(View convertView, int position) {
		viewCache = new ViewCache();
		viewCache.txtKeywords = (TextView) convertView.findViewById(R.id.txt_keywords);
		viewCache.btnDelete = (ImageButton) convertView.findViewById(R.id.btn_delete);
		convertView.setTag(viewCache);
	}

	@Override
	protected void getViewCache(View convertView, int position) {
		viewCache = (ViewCache) convertView.getTag();
	}

	@Override
	protected void setValueByViewCache(View convertView, final int position) {
		final KeywordsVO keywords = getItem(position);
		viewCache.txtKeywords.setText(keywords.getKeywords());
		viewCache.btnDelete.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Builder builder = new Builder(getContext());
				builder.setTitle(R.string.hint);
				builder.setMessage(StringUtil.format("确定要删除“{0}”吗？", keywords.getKeywords()));
				builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();

						boolean isSuccessful = false;
						try {
							isSuccessful = (new FirewallConfigBusiness().delete(keywords.getId()) > 0);
						} catch (Exception e) {
							ExceptionHandler.handle(e, "删除信息拦截关键字时出错");
						}
						if (isSuccessful) {
							getDataSource().remove(position);
							if (!getDataSource().isEmpty()) {
								notifyDataSetChanged();
							} else {
								((FirewallConfigKeywordsActivity) getContext()).setListAdapter(null);
							}
							Toast.makeText(getContext(), R.string.delete_ok, Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(getContext(), R.string.delete_fail, Toast.LENGTH_SHORT).show();
						}
					}
				});
				builder.setNegativeButton(R.string.cancel, null);
				builder.show();
			}
		});
	}
}
